package com.Lacia.emsserver.config;

import cn.hutool.core.util.RandomUtil;
import com.Lacia.emsserver.constant.TopicEmsConst;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class MqttConnection {

    private final MqttConfig mqttConfig;

    private MqttClient mqttClient;



    @PostConstruct
    public void init() {
        log.info("MqttConnection init...");

        try {
            String clientId = mqttConfig.getClientIdPrefix() + "-" + RandomUtil.randomString(6);
            mqttClient = new MqttClient(mqttConfig.getHost(), clientId);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(mqttConfig.getUsername());
            options.setPassword(mqttConfig.getPassword().toCharArray());
            options.setConnectionTimeout(mqttConfig.getConnectionTimeout());
            options.setKeepAliveInterval(10);
            options.setAutomaticReconnect(true);
            mqttClient.setCallback(new MqttMessageCallback(mqttClient, this));
            mqttClient.connect(options);
            log.info("MqttConnection init success");
        } catch (Exception e) {
            log.error("MqttConnectionConfig init error", e);
        }

        subscribeAllEmsTopic();

    }

    public void subscribeAllEmsTopic() {
        var topics = TopicEmsConst.topics();
        for (var topic : topics) {
            subscribe(topic);
        }
    }



    public void publish(String topic, String message) {
        try {
            mqttClient.publish(topic, message.getBytes(), mqttConfig.getQos(), false);
        } catch (Exception e) {
            log.error("MqttConnectionConfig publish error", e);
        }
    }

    public void subscribe(String topic) {
        try {
            mqttClient.subscribe(topic, mqttConfig.getQos());
        } catch (MqttException e) {
            log.error("MqttConnectionConfig subscribe error", e);
        }
    }

    public void unsubscribe(String topic) {
        try {
            mqttClient.unsubscribe(topic);
        } catch (MqttException e) {
            log.error("MqttConnectionConfig unsubscribe error", e);
        }
    }

    @PreDestroy
    public void destroy() {
        try {
            mqttClient.disconnect();
            mqttClient.close();
        } catch (Exception e) {
            log.error("MqttConnection destroy error", e);
        }
    }
}
